<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!-- eslint-disable @typescript-eslint/no-shadow -->
<!-- eslint-disable default-case -->
<script setup lang="tsx">
import { ref, toRefs } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
import { delDept, listDept } from '@/service/api/system/dept';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord, menuTypeRecord } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useDict } from '@/utils/dict';
import DictTag from '@/components/custom/dict-tag.vue';
import type { DeptVO } from '@/service/types/system';
import DeptSearch from './components/dept-search.vue';
import DeptForm from './components/dept-form.vue';
const appStore = useAppStore();
const { sys_normal_disable } = toRefs<any>(useDict('sys_user_sex', 'sys_normal_disable'));
// const { bool: visible, setTrue: openModal } = useBoolean();
const wrapperRef = ref<HTMLElement | null>(null);

const { columns, columnChecks, searchParams, resetSearchParams, data, loading, pagination, getData } = useTable({
  apiFn: listDept,
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    // {
    //   key: 'menuId',
    //   title: $t('page.manage.menu.id'),
    //   align: 'center'
    // },
    {
      key: 'deptName',
      title: '部门名称',
      align: 'center'
    },
    {
      key: 'deptCategory',
      title: '部门编码',
      align: 'center'
    },
    {
      key: 'leaderName',
      title: '负责人',
      align: 'center'
    },
    {
      key: 'status',
      title: '部门状态',
      align: 'center',
      render: (row: DeptVO) => {
        return <DictTag type="badge" value={row.status} dicts={sys_normal_disable.value} />;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      fixed: 'right',
      render: (row: DeptVO) => (
        <div class="flex-center gap-10px">
          <NButton
            text
            tag="a"
            type="primary"
            ghost
            size="small"
            onClick={() => {
              handleEditor(row?.deptId as number);
            }}
          >
            {{
              icon: () => <SvgIcon icon="ant-design:edit-outlined" />
            }}
          </NButton>
          <NPopconfirm
            onPositiveClick={() => {
              handleDelete(row.deptId as number);
            }}
            onNegativeClick={() => {
              (window as any).$message.info('已取消删除');
            }}
          >
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton text tag="a" type="error" ghost size="small">
                  {{
                    icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                  }}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ],
  transformer: (res: any) => {
    // const { records = [], current = 1, size = 10, total = 0 } = res.data || {};
    const { data } = res;
    const recordsWithIndex = data?.data.map((item: any, index: number) => {
      return {
        ...item,
        index: (1 - 1) * data?.data.length + index + 1
      };
    });

    return {
      data: recordsWithIndex,
      pageNum: 1,
      pageSize: 10,
      total: data?.data.length
    };
  },
  showTotal: false,
  apiParams: {
    deptName: null,
    status: null,
    deptCategory: null
  }
});
// 请求删除
const requestRemove = async (deptId: number | number[]): Promise<boolean> => {
  const loadinginstance = (window as any).$message.loading('正在处理中');
  const { data, error } = await delDept(deptId);
  loadinginstance.destroy();
  if (!error) {
    (window as any).$message.success(data?.msg);
    return Promise.resolve(true);
  }
  throw new Error('false');
};

const { handleAdd, checkedRowKeys, onBatchDeleted, drawerVisible, customerEdit, operateType, currentId, onDeleted } =
  useTableOperate(data, getData, 'deptId');

const handleEditor = (id: number) => {
  customerEdit(id);
};
const handleDelete = async (deptId: number) => {
  const result = await requestRemove(deptId as number);
  if (result) {
    onDeleted();
  }
};
const handleBatchDelete = async () => {
  // onBatchDeleted();
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定删除这些吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await requestRemove(checkedRowKeys.value as unknown as number[]);
      if (result) {
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <DeptSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard title="部门管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="(row: DeptVO) => row.deptId"
        remote
        class="sm:h-full"
      >
        <template #empty>
          <Empty />
        </template>
      </NDataTable>
    </NCard>
    <DeptForm
      v-model:visible="drawerVisible"
      :current-id="currentId"
      :sys-normal-disable="sys_normal_disable"
      :operate-type="operateType"
      :depts="data"
      @submitted="getData()"
    />
  </div>
</template>

<style scoped></style>
